<script lang="ts" setup>
import {
  getListByCondition,
  getOneByCondition,
  getOneByConditions,
  getReadonly,
  insertOne,
  reSetDialogModel,
  updateOne,
  urls
} from '@/index';

import type {
  DialogModel,
  NdeCertificationMethod,
  NdeCommissionNdeCommission,
  ProjectWeldList
} from '@/index.d';

import type { FormInstance, FormRules } from 'element-plus';
import { useRequest } from 'vue-request';

const dialogModel = defineModel<DialogModel<NdeCommissionNdeCommission>>('dialogModel', {
  required: true
});

const { insertForbidden, updateForbidden } = getReadonly(dialogModel.value);

const { data: weldList, run: getWeldList } = useRequest(
  () =>
    getListByCondition<ProjectWeldList>(
      urls.projectWeldList,
      'productionReference',
      formData.productionReference as string
    ),
  { manual: true }
);

const projectId = computed(() => {
  if (weldList.value && weldList.value.length > 0) {
    return weldList.value[0].projectId;
  } else {
    return undefined;
  }
});

const formData = reactive<NdeCommissionNdeCommission>({
  id: 0,
  testRatio: '100%'
});

const setWeldInfo = async (res: ProjectWeldList) => {
  formData.projectId = res.projectId;
  formData.componentName = res.componentName;
  formData.partName = res.partName;
  formData.partReference = res.partReference;
  formData.partNameSelection = res.partName;
  formData.partReferenceSelection = res.partReference;
  formData.partQuantity = res.partQuantity;
  formData.partType = res.partType;
  formData.partThickness = res.partThickness;
  formData.weldMethod = res.weldMethod;
  formData.weldMethodStr = res.weldMethodStr;
  formData.weldGroove = res.weldGroove;
  formData.baseMaterial1 = res.baseMaterial1;
  formData.baseMaterial2 = res.baseMaterial2;
  formData.weldMaterial = res.weldMaterial;
  formData.weldMaterialStr = res.weldMaterialStr;
  formData.weldGroove = res.weldGroove;
  formData.ndePersonnelRequirement = res.project?.ndePersonnelRequirement;
};

const setFormData = async (res: NdeCommissionNdeCommission) => {
  formData.id = res.id;
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
  formData.productionReference = res.productionReference;
  formData.ownerId = res.ownerId;
  formData.owner = res.owner;
  formData.ndePersonnelRequirement = res.ndePersonnelRequirement;
  formData.testStage = res.testStage;
  formData.componentName = res.componentName;
  formData.partName = res.partName;
  formData.partReference = res.partReference;
  formData.partQuantity = res.partQuantity;
  formData.partType = res.partType;
  formData.partThickness = res.partThickness;
  formData.partDimension = res.partDimension;
  formData.weldMethod = res.weldMethod;
  formData.weldMethodStr = res.weldMethodStr;
  formData.weldGroove = res.weldGroove;
  formData.baseMaterial1 = res.baseMaterial1;
  formData.baseMaterial2 = res.baseMaterial2;
  formData.weldMaterial = res.weldMaterial;
  formData.weldMaterialStr = res.weldMaterialStr;
  formData.weldGroove = res.weldGroove;
  formData.testPart = res.testPart;
  formData.surfaceStatus = res.surfaceStatus;
  formData.note = res.note;
  formData.method = res.method;
};

const reSetFormData = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  delete formData.projectId;
};

watch(
  () => dialogModel.value.visible,
  value => {
    value && (formData.id = dialogModel.value.id as number);
    !value && reSetFormData();
  },
  {
    immediate: true
  }
);

watch(
  () => formData.id,
  async (value: number | undefined) => {
    if (value) {
      const res = await getOneByCondition<NdeCommissionNdeCommission>(
        urls.ndeCommissionNdeCommission,
        'id',
        value
      );
      res && setFormData(res);
    }
  },
  {
    immediate: true
  }
);

watch(
  () => formData.partNameSelection,
  async (value: string | undefined) => {
    const weldInfo = (await getOneByConditions<ProjectWeldList>(urls.projectWeldList, {
      projectId: projectId.value,
      partName: value
    })) as ProjectWeldList;
    setWeldInfo(weldInfo);
  }
);

watch(
  () => formData.partReferenceSelection,
  async (value: string | undefined) => {
    const weldInfo = (await getOneByConditions<ProjectWeldList>(urls.projectWeldList, {
      projectId: formData.projectId,
      partReference: value
    })) as ProjectWeldList;
    console.log(weldInfo);

    setWeldInfo(weldInfo);
  }
);

const formDataRef = useTemplateRef<FormInstance>('formDataRef');

interface FormDataRules {
  productionReference: string;
  method: NdeCertificationMethod;
  partName: string;
  partReference: string;
  testStage?: string;
  surfaceStatus?: string;
}

const formDataRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});

    case 'update':
      return reactive<FormRules<FormDataRules>>({
        productionReference: [{ required: true, message: '生产令号不能为空', trigger: 'blur' }],
        method: [{ required: true, message: '检测 方法不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '工件名称不能为空', trigger: 'blur' }],
        partReference: [{ required: true, message: '工件编号不能为空', trigger: 'blur' }],
        testStage: [{ required: true, message: '检测时机不能为空', trigger: 'blur' }],
        surfaceStatus: [{ required: true, message: '表面状态不能为空', trigger: 'blur' }]
      });

    case 'insert':
      return reactive<FormRules<FormDataRules>>({
        productionReference: [{ required: true, message: '生产令号不能为空', trigger: 'blur' }],
        method: [{ required: true, message: '检测 方法不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '工件名称不能为空', trigger: 'blur' }],
        partReference: [{ required: true, message: '工件编号不能为空', trigger: 'blur' }],
        testStage: [{ required: true, message: '检测时机不能为空', trigger: 'blur' }],
        surfaceStatus: [{ required: true, message: '表面状态不能为空', trigger: 'blur' }]
      });
  }
});

const saveFormData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (dialogModel.value.id === 0) {
          const res = (await insertOne<NdeCommissionNdeCommission>(
            urls.ndeCommissionNdeCommission,
            formData
          )) as NdeCommissionNdeCommission;
          if (res) {
            setFormData(res);
            dialogModel.value.id = res.id as number;
            dialogModel.value.type = 'update';
            dialogModel.value.change = true;
          }
        } else {
          const tempFormData: NdeCommissionNdeCommission = {
            id: formData.id,
            projectId: formData.projectId,
            method: formData.method,
            partName: formData.partName,
            partReference: formData.partReference,
            partThickness: formData.partThickness,
            partDimension: formData.partDimension,
            partType: formData.partType,
            partQuantity: formData.partQuantity,
            weldMethod: formData.weldMethod,
            baseMaterial1: formData.baseMaterial1,
            baseMaterial2: formData.baseMaterial2,
            weldMaterial: formData.weldMaterial,
            testPart: formData.testPart,
            testStage: formData.testStage,
            surfaceStatus: formData.surfaceStatus,
            testRatio: formData.testRatio,
            thicknessRequirement: formData.thicknessRequirement,
            note: formData.note
          };

          const res = (await updateOne<NdeCommissionNdeCommission>(
            urls.ndeCommissionNdeCommission,
            tempFormData
          )) as NdeCommissionNdeCommission;

          if (res) {
            dialogModel.value.change = true;
            formData.updater = res.updater;
            formData.updateTime = res.updateTime;
          }
        }
      }
    })
    .catch(res => console.log(res));
};

watch(
  () => formData.productionReference,
  _value => getWeldList()
);
</script>
<template>
  <HqDialogDetail
    :dialog-model="dialogModel"
    @submit="saveFormData(formDataRef as FormInstance)"
    operate-record
    :operation="formData"
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <hq-form :model="formData" ref="formDataRef" :rules="formDataRules">
            <el-row :gutter="5">
              <hq-col v-show="false">
                <el-form-item label="id" prop="id">
                  <el-input v-model="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col v-show="false">
                <el-form-item label="委托编号" prop="commissionReference">
                  <el-input v-model="formData.commissionReference" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="生产令号" prop="productionReference" style="width: 100%">
                  <el-select
                    v-model="formData.productionReference"
                    filterable
                    clearable
                    :disabled="insertForbidden"
                  >
                    <HqProjectProductionReference />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="检测方法" prop="method">
                  <el-select v-model="formData.method" :disabled="insertForbidden">
                    <HqNdeMethodOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col v-if="dialogModel.type !== 'view'">
                <el-form-item label="工件名称（索引）" prop="partNameSelection">
                  <el-select
                    v-model="formData.partNameSelection"
                    clearable
                    :disabled="insertForbidden"
                  >
                    <el-option
                      v-for="weld in weldList"
                      :key="weld.id"
                      :value="weld.partName!"
                      :label="weld.partName!"
                    />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col v-if="dialogModel.type !== 'view'">
                <el-form-item label="工件编号（索引）" prop="partReferenceSelection">
                  <el-select
                    v-model="formData.partReferenceSelection"
                    clearable
                    :disabled="insertForbidden"
                  >
                    <el-option
                      v-for="weld in weldList"
                      :key="weld.id"
                      :value="weld.partReference!"
                      :label="weld.partReference!"
                    />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件名称" prop="partName">
                  <el-input v-model="formData.partName" :disabled="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件编号" prop="partReference">
                  <el-input v-model="formData.partReference" :disabled="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件数量" prop="partQuantity">
                  <el-input-number
                    v-model="formData.partQuantity"
                    :disabled="updateForbidden"
                    :min="1"
                    :step="1"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="焊接方法" prop="weldMethod">
                  <el-select v-model="formData.weldMethod" :disabled="updateForbidden" multiple>
                    <el-option value="N/A" label="N/A" />
                    <HqDictionary type-text="焊接方法" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="母材1牌号" prop="baseMaterial1">
                  <el-select v-model="formData.baseMaterial1" :disabled="updateForbidden" clearable>
                    <template #default>
                      <el-option value="N/A" label="N/A" />
                      <HqDictionary type-text="母材牌号" />
                    </template>
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="母材2牌号" prop="baseMaterial2">
                  <el-select v-model="formData.baseMaterial2" :disabled="updateForbidden" clearable>
                    <el-option value="N/A" label="N/A" />
                    <HqDictionary type-text="母材牌号" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="填充材料" prop="weldMaterial">
                  <el-select
                    v-model="formData.weldMaterial"
                    :disabled="updateForbidden"
                    multiple
                    clearable
                  >
                    <el-option value="N/A" label="N/A" />
                    <HqDictionary type-text="焊材牌号" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件厚度" prop="partThickness">
                  <el-input-number
                    v-model="formData.partThickness"
                    :min="0"
                    :step="0.01"
                    :disabled="updateForbidden"
                    controls-position="right"
                  >
                    <template #suffix>mm</template>
                  </el-input-number>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件尺寸" prop="partDimension">
                  <el-input v-model="formData.partDimension" :disabled="updateForbidden">
                    <template #suffix>mm</template>
                  </el-input>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="检测时机" prop="testStage">
                  <el-select v-model="formData.testStage" :disabled="updateForbidden">
                    <HqDictionary type-text="检测时机" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件类型" prop="partType">
                  <el-select v-model="formData.partType" :disabled="updateForbidden">
                    <HqDictionary type-text="焊缝类型" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="检测部位" prop="testPart">
                  <el-select v-model="formData.testPart" :disabled="updateForbidden">
                    <HqDictionary type-text="检测部位" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="表面状态" prop="surfaceStatus">
                  <el-select v-model="formData.surfaceStatus" :disabled="updateForbidden">
                    <el-option value="机加工" label="机加工" />
                    <el-option value="打磨" label="打磨" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="检测比例" prop="testRatio">
                  <el-input v-model="formData.testRatio" :disabled="updateForbidden" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="焊接坡口" prop="weldGroove">
                  <el-select v-model="formData.weldGroove" :disabled="updateForbidden">
                    <el-option value="N/A" label="N/A" />
                    <HqDictionary type-text="焊接坡口" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col v-if="formData.method == 'CH'">
                <el-form-item label="厚度要求" prop="thicknessRequirement">
                  <el-input v-model="formData.thicknessRequirement" :readonly="updateForbidden">
                    <template #suffix>mm</template>
                  </el-input>
                </el-form-item>
              </hq-col>
            </el-row>

            <el-row>
              <el-form-item label="备注" prop="note" style="width: 100%">
                <el-input
                  v-model="formData.note"
                  type="textarea"
                  :autosize="{ minRows: 5 }"
                  :readonly="updateForbidden"
                />
              </el-form-item>
            </el-row>
          </hq-form>
        </template>
      </el-card>

      <el-card shadow="hover" v-if="formData.attachmentUuid">
        <template #header>附件</template>

        <template #default>
          <HqUploadOne
            :key-word="formData.attachmentUuid"
            :disabled="dialogModel.type !== 'update'"
          />
        </template>
      </el-card>
    </template>
  </HqDialogDetail>
</template>
<style lang="scss" scoped></style>
